<?php if(empty($this->getUpdate) && empty($this->checkUpdate)): ?>
<script>
    jQuery.noConflict();
//    jQuery(document).ready(function(jQuery) {
//        
//    });
    function createProfileInfoPopup(){
        //console.log('create profile popup!');
        var temp = new Array();
        
        temp.combine($$('.feed_item_bodytext > a'));
        temp.combine($$('.comments_likes > a'));
        temp.combine($$('.feed_item_bodytext > a'));
        temp.combine($$('.feed_item_posted > a'));
        temp.combine($$('.feed_item_generated > a'));
        temp.combine($$('.feed_item_photo > a'));
        temp.combine($$('.comments_author_photo > a'));
        temp.combine($$('.comments_author > a'));
        
        temp.each(function(el){
            var index = null;
            var href = el.getAttribute('href');
            //if (en4.core.staticBaseUrl != '/')
            //href = href.replace(en4.core.staticBaseUrl, '');
            if ((index = href.search('profile/')) != -1){
                //console.log(el.getAttribute('href'));
				//Fix bug like
				pva = href.substring(index+8);
				if (pva.search('/')  == -1){
					el.addClass("walltip");
					el.setAttribute('tiptype', 'user');
					var username_or_user_id = pva;
					if (isNaN(username_or_user_id)){
						el.setAttribute('uname', username_or_user_id);
					} else {
						el.setAttribute('uid', username_or_user_id);
					}
					var divTooltip = new Element('div', {'class': 'tooltip'});
					divTooltip .inject(el, 'after');
				}
            }
            
            if ((index = href.search('group/')) != -1){
                //console.log(el.getAttribute('href'));
                el.addClass("walltip");
                el.setAttribute('tiptype', 'group');
                var group_id = href.substring(index+6);
                el.setAttribute('uid', group_id);
                var divTooltip = new Element('div', {'class': 'tooltip'});
                divTooltip .inject(el, 'after');
            }
        });
    }
    window.addEvent('domready', function(){
        createProfileInfoPopup();
        //http://flowplayer.org/tools/forum/30/37281
        jQuery(document).delegate(".walltip", "mouseenter", function() {
            if (!jQuery(this).data("tooltip")) {
                tip = jQuery(this);
                jQuery.ajax({
                    type: "POST",
                    url: "wall/index/get-user-info",
                    data: 'id=' + jQuery(this).attr('uid') + '&' + 'name=' + jQuery(this).attr('uname') + '&' + 'type=' + jQuery(this).attr('tiptype'),
                    async:false
                }).done(function( data ) {
                    tip.next('div').html(data);
                });
                tip.tooltip();
                tip.trigger("mouseenter");
            }
        });
    });
</script>
<script> 
    window.addEvent('domready', function(){
        if (!$('wall-compose-submit')) return;
        $('wall-compose-submit').addEvent('click', function(e){
            e.stop();
            composeInstance.saveContent();
            if (checkStatusBody('wall_body', composeInstance.pluginReady)){
                var last_id = 0;
                $('wall-activity-form').set('send', {
                    async: false,
                    onSuccess: function(responseText){
                        last_id = parseInt(responseText);
                        if (typeof activityUpdateHandler == 'object'){
                            activityUpdateHandler.options.last_id = last_id;
                        }
                        
                        $('wall_body').value = '';
                        $('wall_body').setStyle('height','22px');
                        $('wall_body').fireEvent('blur');
                        $('wall_body_body_html').value = '';
                        $('wall_body_tagged_users').value = '';
                        $('wall_body_hightlighter').innerHTML = '';
                        $('wall_body_hightlighter').setStyle('height','22px');
                        
                        composeInstance.setContent('');
                        if (composeInstance.plugins.video != undefined){
                          composeInstance.plugins.video.params.video_id = 0;
                        }
                        
                        if (composeInstance.plugins.music != undefined){
                          composeInstance.plugins.music.params.song_id = 0;
                        }
                        
                        composeInstance.deactivate();
                        _ynwallsubmiting = false;
                        if ($('nothing-tip') != undefined){
                          $('nothing-tip').style.display = 'none';
                        }
                        if ($('nothing-tip2') != undefined){
                          $('nothing-tip2').style.display = 'none';
                        }
                    }
                });
                
                $('wall-activity-form').send();
                if($('feed_loading2')) {
                	$('feed_loading2').style.display = '';
                }

                en4.core.request.send(new Request.HTML({
                    url : en4.core.baseUrl + 'widget/index/name/activity.feed',
                    data : {
                        'format' : 'html',
                        'minid' : last_id,
                        'feedOnly' : true,
                        'nolayout' : true,
                        'subject' : '<?php echo $this->subjectGuid ?>',
                        'countAutoload':<?php echo $this->countAutoload?>,                        
                        'filter_type':'default',
                        'filter_id':null,
                        'getUpdate':true
                    },
                    onComplete: function(){
                    	if($('feed_loading2')) {
                        	$('feed_loading2').style.display = 'none';
                    	}
                    }
                }), {
                    'element' : $('activity-feed'),
                    'updateHtmlMode' : 'prepend',
                    'createProfileInfoPopup': true
                });
            }         
        });
        
    });
var countAutoload = <?php echo $this->countAutoload?>;
var end = <?php echo ( $this->endOfFeed ? 'true' : 'false' ) ?>;
var running = false;
var noFeed = <?php echo ( $this->noFeed ? 'true' : 'false' ) ?>;

//Bat su kien scroll
var spy;
var spyContainer = window;
window.removeEvents('scroll');
var min = spyContainer.getScrollSize().y - spyContainer.getSize().y -50; /*- 150 tolerance */
spy = new ScrollSpy({
    container: spyContainer,
    min: min,
    onEnter: function() {
        //console.log('scroll', countAutoload);
        //console.log('end = ', end);
            if ($('nothing-tip2') && $('nothing-tip2').getStyle('display') == 'block') return;
            if (!end && countAutoload <= <?php echo $this->autoload_feed_limit ?>){
                $('feed_viewmore_link').fireEvent('click');
            } else {
                console.log('stop autoload');
            }
        }
});
//End
</script>
<?php endif;?>
<?php if( (!empty($this->feedOnly) || !$this->endOfFeed )&& (empty($this->getUpdate) && empty($this->checkUpdate))): ?>
<script type="text/javascript">
(function(){
    var activity_count = <?php echo sprintf('%d', $this->activityCount) ?>;
    var next_id = <?php echo sprintf('%d', $this->nextid) ?>;
    var subject_guid = '<?php echo $this->subjectGuid ?>';
    var endOfFeed = <?php echo ( $this->endOfFeed ? 'true' : 'false' ) ?>;
    var activityViewMore = function(next_id, subject_guid) {
        if( en4.core.request.isRequestActive() ) return;
        var url = '<?php echo $this->url(array('module' => 'core', 'controller' => 'widget', 'action' => 'index', 'content_id' => $this->identity), 'default', true) ?>';
        $('feed_viewmore').style.display = 'none';
        $('feed_loading').style.display = '';
        
        var request = new Request.HTML({
            url : url,
            data : {
                format : 'html',
                'maxid' : next_id,
                'feedOnly' : true,
                'nolayout' : true,
                'subject' : subject_guid,
                'countAutoload':<?php echo $this->countAutoload ?>, //gui them bien count sang server
                'filter_type':'<?php echo $this->filter_type ?>',
                'filter_id':'<?php echo $this->filter_id ?>'
            },
            evalScripts : true,
            onRequest: function(){
                running = true;  
            },
            onSuccess : function(responseTree, responseElements, responseHTML, responseJavaScript) {		
                Elements.from(responseHTML).inject($('activity-feed'));
                en4.core.runonce.trigger();
                Smoothbox.bind($('activity-feed'));
                running = false;
                createProfileInfoPopup();
            }
        });
        if (!running){
            request.send();   
        }
    }

    en4.core.runonce.add(function(){
        if( next_id > 0 && !endOfFeed ) {
            $('feed_viewmore').style.display = '';
            $('feed_loading').style.display = 'none';

            $('feed_viewmore_link').removeEvents('click').addEvent('click', function(event){
                if (event != undefined){
                    event.stop();   
                }
                activityViewMore(next_id, subject_guid);
            });
        } else {
            $('feed_viewmore').style.display = 'none';
            $('feed_loading').style.display = 'none';
        }
    });
})();

</script>
<?php endif; ?>
<?php if( !empty($this->feedOnly) && empty($this->checkUpdate)): // Simple feed only for AJAX
  echo $this->wallLoop($this->activity, array(
    'action_id' => $this->action_id,
    'viewAllComments' => $this->viewAllComments,
    'viewAllLikes' => $this->viewAllLikes,
  ));
  return; // Do no render the rest of the script in this mode
endif; ?>
<?php if( !empty($this->checkUpdate) ): // if this is for the live update
  if ($this->activityCount)
  echo "<script type='text/javascript'>
          document.title = '($this->activityCount) ' + activityUpdateHandler.title;
        </script>

        <div class='tip'>
          <span>
            <a href='javascript:void(0);' onclick='javascript:activityUpdateHandler.getFeedUpdate(".$this->firstid.");$(\"feed-update\").empty();'>
              {$this->translate(array(
                  '%d new update is available - click this to show it.',
                  '%d new updates are available - click this to show them.',
                  $this->activityCount),
                $this->activityCount)}
            </a>
          </span>
        </div>";
  return; // Do no render the rest of the script in this mode
endif; ?>
<?php if( !empty($this->getUpdate) ): // if this is for the get live update ?>
   <script type="text/javascript">
     activityUpdateHandler.options.last_id = <?php echo $this->firstid;?>;
   </script>
<?php endif; ?>

<?php if( $this->enableComposer ): ?>
  <div style="display:none"><textarea name="body"></textarea></div>
  <div class="activity-post-container" style="overflow:visible;">
    <form style="overflow:visible;" method="post" action="<?php echo $this->url(array('module' => 'wall', 'controller' => 'index', 'action' => 'post'), 'default', true) ?>" class="activity" enctype="application/x-www-form-urlencoded" id="wall-activity-form">
    	
    	<div style="position:relative;overflow:visible;">
    		<textarea id="wall_body" cols="1" rows="1" name="body" placeholder="<?php echo $this->translate("What's on your mind?")?>"><?php echo $this->translate("What's on your mind?")?></textarea>        
    	<input type="hidden" name="privacy" id="privacy_set" value="0" />
        <input type="hidden" name="return_url" value="<?php echo $this->url() ?>" />
        <?php if( $this->viewer() && $this->subject() && !$this->viewer()->isSelf($this->subject())): ?>
          <input type="hidden" name="subject" value="<?php echo $this->subject()->getGuid() ?>" />
        <?php endif; ?>    		
    	</div>
    	<div id="fly_wall_composer">
      <table cellpadding="0" cellspacing="0" border="0" width="100%" id="composer_table" style="display: none">
          <tr>
              <td style="padding-top: 2px"><div id="menu_editor">
                    <div id="compose-menu" class="compose-menu" style="overflow:visible; margin-right: -2px">
	                  <button id="wall-compose-submit" type="submit" style="float:right; margin-right: 0px;" onclick="return false;"><?php echo $this->translate("Share") ?></button>
                          <?php if ($this->enable_privacy): ?>
	                  <div id="wall_privacy" style="overflow:visible; float:right; margin: -2px 3px 3px 5px;padding: 0;">
	                      <a id="lock" href="javascript:void(0);">
	                          <img title="Share with" id="lock_img" alt="share with" src="<?php echo $this->baseUrl() ?>/application/modules/Wall/externals/images/l1.png" border="0" />
	                      </a>
	                      <ul id="fly_privacy">
	                      	<li id="txt_pri0" onclick="setPrivacy(0);" class="privacy-item"><?php echo $this->translate("Everyone")?></li>
	                      	<li id="txt_pri1" onclick="setPrivacy(1);" class="privacy-item"><?php echo $this->translate("Friends of Friends")?></li>
	                      	<li id="txt_pri2" onclick="setPrivacy(2);" class="privacy-item border_bottom"><?php echo $this->translate("Friends Only")?></li>
                                <li>
                                    <ul>
                                    <?php 
                                        $i = 2;
                                        foreach ($this->custom_lists as $list): 
                                            $i++;
                                    ?>
                                    <li class="privacy-item" id="txt_pri<?php echo $i ?>" listid="<?php echo $list->list_id?>" onclick="setPrivacy(<?php echo $i ?>);">
                                        <div class="list_name">
                                            <?php echo $list->list_name?>
                                        </div>
                                        <div class="action_list">
                                            <img class="edit_list" listid="<?php echo $list->list_id?>" src="application/modules/Wall/externals/images/edit.png"/>
                                            <img class="delete_list" listid="<?php echo $list->list_id?>" src="application/modules/Wall/externals/images/delete.png"/>
                                        </div>
                                    </li>

                                    <?php endforeach;?>
                                    </ul>
                                </li>
                                <li id="create_list" class="privacy-item" onclick="createPopUp();">
                                    <div style="padding-left: 24px; clear:both; border-top: 1px solid #EAEAEA"><?php echo $this->translate("Create a Custom List")?></div>
                                </li>
	                      </ul>
                              <script type="text/javascript">
                                // should add event click to the last <li> tag 
                                $('create_list').addEvent('click', function(){
                                  var sb_url = '<?php echo $this->url(array('action' => 'create'), 'wall_list', true) ?>?uid=2';
                                  Smoothbox.open(sb_url);
                                });

                                $$('.delete_list').each(function(element, key) {
                                  element.addEvent('click', function(){
                                     //alert('delete ' +  this.get('listid')); 
                                    var sb_url = '<?php echo $this->url(array('action' => 'delete'), 'wall_list', true) ?>?listid=' + this.get('listid');
                                    Smoothbox.open(sb_url);
                                  });
                                });

                                $$('.edit_list').each(function(element, key) {
                                  element.addEvent('click', function(){
                                     //alert('edit ' +  this.get('listid')); 
                                     var sb_url = '<?php echo $this->url(array('action' => 'edit'), 'wall_list', true) ?>?listid=' + this.get('listid');
                                     Smoothbox.open(sb_url);
                                  });
                                });

                                function setPrivacy(privacy) {
                                  for(var i = 0; i <= <?php echo $i?>; ++i) {
                                      if(i == privacy) {
                                          $('txt_pri'+i).addClass('active');
                                      } else {
                                          $('txt_pri'+i).removeClass("active");
                                      }
                                  }
                                  $('fly_privacy').hide();
                                  $('privacy_set').set('value', privacy);
                                  if (privacy > 2){
                                      $('privacy_set').set('value', $('txt_pri' + privacy).get('listid'));
                                  }
                                }
                              </script>
                              
	                  </div>
                          <?php endif; ?>
                  </div>
                  </div>                 
              </td>
          </tr>
      </table>
      </div>
      <div id="compose-tray" class="compose-tray" style="display: none;"></div>
      <div style="clear:both"></div>            
    </form>

<script type="text/javascript">
    var composeInstance;
    en4.core.runonce.add(function() {
      composeInstance = new Composer('wall_body', {
          menuElement : 'compose-menu',
          trayElement: 'compose-tray',
          baseHref : '<?php echo $this->baseUrl() ?>',
          lang : {
              'Post Something...' : '<?php echo $this->translate('Post Something...') ?>'
          }
      });
    });
    // register event whenever loaded data.
    var ynfriends = { rows: <?php echo Zend_Json::encode($this->friendUsers); ?> };
    $(window).addEvent('domready', function(){
      if($('wall_body')){
          ynwall('wall_body');	
      }	
      if($('fly_privacy')){
          initPrivacy();
      }
    });
    <?php if ($this->updateSettings && !$this->action_id): // wrap this code around a php if statement to check if there is live feed update turned on  ?>
    var activityUpdateHandler;
    en4.core.runonce.add(function() {
        try {
            activityUpdateHandler = new ActivityUpdateHandler({
                'baseUrl' : en4.core.baseUrl,
                'basePath' : en4.core.basePath,
                'identity' : 4,
                'delay' : <?php echo $this->updateSettings; ?>,
                'last_id': <?php echo (int) $this->firstid; ?>,
                'subject_guid' : '<?php echo $this->subjectGuid ?>',
                'filter_type':'<?php echo $this->filter_type ?>',
                'filter_id':'<?php echo $this->filter_id ?>'
                //'ajax_call':true
            });
            setTimeout("activityUpdateHandler.start()",10250);
            //activityUpdateHandler.start();
            window._activityUpdateHandler = activityUpdateHandler;
        } catch( e ) {
            //if( $type(console) ) console.log(e);
        }
    });
    <?php endif; ?>
</script>

    <?php foreach( $this->composePartials as $partial ): ?>
      <?php echo $this->partial($partial[0], $partial[1]) ?>
    <?php endforeach; ?>

  </div>
  
<?php if ($this->enable_privacy): ?>
<div id="filter-container">
    <span id="filter-button"><span id="filter-button-title"><?php echo $this->translate('FILTER');?>: MOST RECENT</span><img src="application/modules/Wall/externals/images/arrow-filter.png"/></span>
    <ul id="filter">
        <li class="active border_bottom filter-item" filter_type="default"><?php echo $this->translate('Most Recent');?></li>
        <li class="border_bottom filter-item"filter_type="friend"><?php echo $this->translate('Friends');?></li>
        <li class="border_bottom"><span class="filter_title"><?php echo $this->translate('Content');?></span>
            <ul>
                <li class="filter-item" filter_type="status"><?php echo $this->translate('Status');?></li>
                <li class="filter-item" filter_type="blog"><?php echo $this->translate('Blogs');?></li>
                <li class="filter-item" filter_type="album"><?php echo $this->translate('Albums');?></li>
            </ul>
        </li>
        <li><span class="filter_title"><?php echo $this->translate('List');?></span>
            <ul>
                <?php 
		foreach ($this->custom_lists as $list): 
		?>
		<li class="filter-item" filter_type="list" filter_id="<?php echo $list->list_id?>"><?php echo $list->list_name;?></li>
		<?php endforeach;?>
            </ul>
        </li>
    </ul>
</div>
<script>
var filter_status = false;
var filter_count_down = 1;

function truncate (text, limit, append) {
    if (typeof text !== 'string')
        return '';
    if (typeof append == 'undefined')
        append = '...';
    var parts = text.split(' ');
    if (parts.length > limit) {
        // loop backward through the string
        for (var i = parts.length - 1; i > -1; --i) {
            // if i is over limit, drop this word from the array
            if (i+1 > limit) {
                parts.length = i;
            }
        }
        // add the truncate append text
        parts.push(append);
    }
    // join the array back into a string
    return parts.join(' ');
}

window.addEvent('domready', function(){    
        $('filter-button').addEvent('click', function(){
            if(filter_status){
                filter_count_down = 1;
            }
            $('filter').toggle();
            filter_status = filter_status ? false : true;
        });
        $(document).addEvent('click', function() {
		if(filter_status && filter_count_down <= 0) {
			$('filter').hide();
                        filter_count_down = 1;
                        filter_status = false;
		} else if(filter_status) {
			filter_count_down = (filter_count_down <= 0) ? 0 : --filter_count_down;
		}
	});
        $('filter').getElements('li.filter-item').each(function(el){
            el.addEvent('click', function(e){
                if ($('nothing-tip')){
                    $('nothing-tip').style.display = 'none';
                }
                //Select the item
                $('filter').getElements('li.filter-item').each(function(el){
                    el.removeClass('active');
                });

                this.addClass('active');
                $('filter-button-title').set('text', '<?php echo $this->translate('FILTER');?>' + ' : ' + truncate(this.get('text').toUpperCase(), 3));
                
                //Update content
                //Clear all old content
                $('activity-feed').empty();

                //Get params
                var filter_type = el.getAttribute('filter_type');
                var filter_id = el.getAttribute('filter_id');

                if (typeof activityUpdateHandler == 'object'){
                    activityUpdateHandler.options.filter_type = filter_type;
                    activityUpdateHandler.options.filter_id = filter_id;
                }
                //Send request and update content
                if (typeof activityUpdateHandler == 'Object'){
                    last_id = activityUpdateHandler.options.last_id
                } else {
                    last_id = 0;
                }
                var url = '<?php echo $this->url(array('module' => 'core', 'controller' => 'widget', 'action' => 'index', 'content_id' => $this->identity), 'default', true) ?>';
                en4.core.request.send(new Request.HTML({
                    //url : en4.core.baseUrl + 'widget/index/name/activity.feed',
                    url : url,
                    data : {
                        'format' : 'html',
                        'last_id' : 0,
                        'feedOnly' : true,
                        'nolayout' : true,
                        'subject' : '<?php echo $this->subjectGuid ?>',
                        'filter_type':filter_type,
                        'filter_id':filter_id
                    },
                    onRequest: function(){
                        $('activity-feed').setStyle('min-height', '400px');
                        if($('feed_loading2')) {
                        	$('feed_loading2').style.display = '';
                        }
                        if ($('feed_viewmore')){
                            $('feed_viewmore').style.display = 'none';
                        }
                        if ($('nothing-tip2')){
                            $('nothing-tip2').style.display = 'none';
                        }
                    },
                    onComplete: function(){
                    	if($('feed_loading2')) {
                            $('feed_loading2').style.display = 'none';
                        }
                        var endOfFeed = <?php echo ( $this->endOfFeed ? 'true' : 'false' ) ?>;
                        var next_id = <?php echo sprintf('%d', $this->nextid) ?>;

                        if( next_id > 0 && !endOfFeed ) {
                            $('feed_viewmore').style.display = '';
                        }

                        if(noFeed){
                            if ($('nothing-tip2')){
                                $('nothing-tip2').style.display = '';
                                end = true;
                            }
                        }
                    }
                }), {
                    'element' : $('activity-feed'),
                    'updateHtmlMode' : 'append',
                    'createProfileInfoPopup': true,
                    'checkViewMore': true
                });
            });
        });
        $('filter').getFirst('li.filter-item').addClass('active');
    });
</script>
<div class="tip" id="nothing-tip2" style="display:none">
  <span>
    <?php echo $this->translate("Nothing found!") ?>
  </span>
</div>
<?php endif; //End If enable_privacy?>
<?php endif; //End If enableCompuser?>
<div id="feed_loading2" style="display: none; padding-bottom: 10px">
  <img src='application/modules/Core/externals/images/loading.gif' style='float:left;margin-right: 5px;' />
  <?php echo $this->translate("Loading ...") ?>
</div>
<?php // If requesting a single action and it doesn't exist, show error ?>
<?php if( !$this->activity ): ?>
  <?php if( $this->action_id ): ?>
    <h2><?php echo $this->translate("Activity Item Not Found") ?></h2>
    <p>
      <?php echo $this->translate("The page you have attempted to access could not be found.") ?>
    </p>
  <?php return; else: ?>
    <div class="tip" id="nothing-tip">
      <span>
        <?php echo $this->translate("Nothing has been posted here yet - be the first!") ?>
      </span>
    </div>
    <div id="feed-update"></div>
    <ul class='feed' id="activity-feed"></ul>
  <?php return; endif; ?>
<?php endif; ?>
<div id="feed-update"></div>
<ul class='feed' id="activity-feed">
<?php 
  echo $this->wallLoop($this->activity, array(
    'action_id' => $this->action_id,
    'viewAllComments' => $this->viewAllComments,
    'viewAllLikes' => $this->viewAllLikes,
  ))
?>
</ul>

<div class="feed_viewmore" id="feed_viewmore" style="display: none;">
  <?php echo $this->htmlLink('javascript:void(0);', $this->translate('View More'), array(
    'id' => 'feed_viewmore_link',
    'class' => 'buttonlink icon_viewmore'
  )) ?>
</div>

<div class="feed_viewmore" id="feed_loading" style="display:none">
  <img src='application/modules/Core/externals/images/loading.gif' style='float:left;margin-right: 5px;' />
  <?php echo $this->translate("Loading ...") ?>
</div>
